package queue_stack.nowcoder.easy;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author Stark
 * @description 合法括号序列判断
 * 题目链接:https://www.nowcoder.com/practice/d8acfa0619814b2d98f12c071aef20d4?
 * tpId=8&&tqId=11039&rp=1&ru=/activity/oj&qru=/ta/cracking-the-coding-interview/question-ranking
 * @date 2022/4/25 17:24
 **/
public class Parenthesis {
    public boolean chkParenthesis(String A, int n) {
        if(A == null || n <= 0 || A.charAt(0) != '(' || n % 2 != 0){
            return false;
        }
        Queue<Character> queue = new ArrayDeque<>();
        for(int i = 0;i < n;i++){
            char ch = A.charAt(i);
            if(ch == '('){
                queue.offer(ch);
            }else if(ch == ')'){
                if(queue.size() == 0 || queue.poll() != '('){
                    return false;
                }
            }else{
                return false;
            }
        }
        return true;
    }
}